import java.io.IOException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;

public class Add implements Command {
	public ArrayList<Task> tasks;
	public AddParser addParser;
	public Storage storage;
	public History history;
	public Logger logger;
	String data;
	String errorMessage;
	String output;
	private boolean isError = false;

	private static final String ADD_SUCCESSFUL = "\" %s \"  is added successfully.\n";
	private static final String ADD_UNSUCCESSFUL = "\" %s \"  is added unsuccessfully.\n";
	private static final String COMMAND_ADD = "add";

	public Add(ArrayList<Task> tasks, Storage storage, History history,
			Logger logger) {
		this.tasks = tasks;
		this.addParser = new AddParser();
		this.storage = storage;
		this.history = history;
		this.logger = logger;
		errorMessage = "";
	}

	@Override
	public void acceptInput(String data) {
		// TODO Auto-generated method stub
		this.data = data;

	}

	@Override
	public void execute() {
		// TODO Auto-generated method stub
		Task newTask = null;
		try {
			newTask = addParser.parse(data, tasks);
		} catch (ParseException e) {
			errorMessage = e.getMessage();
			// TODO Auto-generated catch block
			logger.log(Level.INFO, errorMessage);
			e.printStackTrace();
			// return errorMessage;
		}

		if (newTask == null) {
			output = String.format(ADD_UNSUCCESSFUL, data);
		} else {

			history.storeUndo(tasks, COMMAND_ADD);

			tasks.add(newTask);
			output = String.format(ADD_SUCCESSFUL, newTask.getUserInput());
		}
	}

	@Override
	public String outputToUser() {
		// TODO Auto-generated method stub

		if (!errorMessage.equals("")) {
			output = errorMessage;
			isError = true;
		}
		return output;
	}

	@Override
	public String save() throws IOException {
		// TODO Auto-generated method stub
		return storage.writeToStorage(tasks);
	}

	@Override
	public boolean isError() {
		// TODO Auto-generated method stub
		return isError;
	}
}